<template>
    <div 
    class="container" 
    v-if="visible" 
    :class="{'container-out':closeAnimation}"
    :style="`animation-duration:${!closeAnimation ? openTime/1000 : closeTime/1000}s;`">
        <!-- 头部 -->
        <div class="text-header">
            <div>
                <svgIcon iconName="icon-wodeyouxiang"/>
                <span>{{ commentTitle }}</span>
            </div>
            <Close 
            :size="24" 
            v-if="showCloseButton"
            @click="closeButton"></Close>
        </div>
        <!-- 留言 -->
        <div class="conmment-main">
            <textarea 
            v-model="commentText"
            :placeholder="textareaPlaceholder" 
            @keydown.ctrl.enter="commentSubmit"
            title="ctrl+enter 快速提交"
            maxlength="1000" 
            class="comment-textarea"></textarea>
            <div class="operation">
                <!-- 表情 -->
                <div></div>
                <!-- 提交 -->
                <button >
                    <span class="shadow"></span>
                    <span class="edge"></span>
                    <span class="front text" @click="commentSubmit">提交</span>
                </button>
            </div>
        </div>
    </div>
</template>

<script setup>
import svgIcon from '@/components/system/svgicon/svgicon.vue';
import { ref, reactive, onBeforeMount, computed, watch } from 'vue';
import { throttle } from '@/utils/countdown-util';
import Close from '@/components/animation/close/close.vue';
import { commentApi } from '@/api/article/comment-api';
import { ElMessage } from 'element-plus';
import { useUserStore } from '@/store/system/user';
import { goAnchor, trimSpaces } from '@/utils/tools-util';

// ========================= 实列挂载之前调用 =========================
// 数据初始化
onBeforeMount(() => {
    closeAnimation.value = false;
});

// ========================= 接收值 =========================
const props = defineProps({
    // 是否显示当前组件
    visible: {
        type: Boolean,
        default: true
    },

    // 标题内容
    commentTitle: {
        type: String,
        default: '留言'
    },

    // 提示内容
    textareaPlaceholder: {
        type: String,
        default: '快来发表你的观点吧'
    },

    // 是否显示按钮
    showCloseButton: {
        type: Boolean,
        default: false
    },

    // 组件打开动画持续时间,单位毫秒
    openTime: {
        type: Number,
        default: 200
    },

    // 组件关闭动画持续时间,单位毫秒
    closeTime: {
        type: Number,
        default: 200
    },

    commentType: {
        type: Number,
        default: 0
    },
    submitInfo: {
        type: Object,
        default: ()=>{}
    }
});

// ========================= 提交评论 =========================
const emit = defineEmits();             // 向父组件传值
let commentText = ref('');              // 评论文本内容
let commentForm = reactive({
    articleId:'',                               // 文章id
    userId:'',                                  // 用户主键id
    articleTitle:'',                            // 文章标题
    parentId:'0',                               // 父级评论id
    type: props.commentType,                    // 评论类别
    fromUserId:'',                              // 评论用户id
    fromNickname:'',                            // 评论用户昵称
    fromAvatar:'',                              // 评论用户头像
    toUserId:'',                                // 回复评论用户Id
    toNickname:'',                              // 回复评论名称
    toAvatar:'',                                // 回复评论用户头像
    toId:'',                                    // 回复评论id
    toUserKeyId:'',                             // 被回复的用户主键id
    content:'',                                 // 评论内容
    createdAt:'',                               // 创建时间
    updatedAt:'',                               // 更新时间
});
async function commentSubmit() {
    try {
        if(!throttle()) return;
        if(!token) return ElMessage.error('请先登录！');
        commentText.value = trimSpaces(commentText.value);
        if (!isValidComment(commentText.value)) return;
        setForm(props.submitInfo);
        const res = await commentApi.create(commentForm);
        if(res.meta.status !== 200) throw new Error(res.meta.msg);
        ElMessage.success('评论成功');
        commentText.value = '';
        resetForm();
        (props.submitInfo && props.submitInfo.fromUserId) && closeButton();
        emit('commentSubmit');
    } catch (e) {
        console.error(e);
        ElMessage.error(e.message);
    };
};

// 按钮关闭
let closeAnimation = ref(false);
function closeButton() {
    closeAnimation.value = true;
    setTimeout(()=> {
        emit('closeButton', false);
        closeAnimation.value = false;
    }, props.closeTime);
};

// 设置评论的请求信息
const { id, token, userId, nickname, avatar} = useUserStore();
function setForm(item) {
    let date = new Date();
    if(item && item.fromUserId) {
        commentForm.articleId = item.articleId;
        commentForm.articleTitle = item.articleTitle;
        commentForm.userId = id;
        item.parentId === '0' ? 
        commentForm.parentId = item.id : 
        commentForm.parentId = item.parentId;
        commentForm.fromUserId = userId;
        commentForm.fromNickname = nickname;
        commentForm.fromAvatar = avatar;
        commentForm.toUserId = item.fromUserId;
        commentForm.toNickname = item.fromNickname;
        commentForm.toAvatar = item.fromAvatar;
        commentForm.toId = item.id;
        commentForm.toUserKeyId = item.userId;
        commentForm.content = commentText.value;
        commentForm.createdAt = date;
        commentForm.updatedAt = date;
    }else {
        item && (commentForm.articleId = item.id);
        item && (commentForm.articleTitle = item.articleTitle);
        // 没有文章信息的评论，不需要携带
        !item && delete commentForm.articleId;
        !item && delete commentForm.articleTitle;
        commentForm.userId = id;
        commentForm.parentId = '0';
        commentForm.fromUserId = userId;
        commentForm.fromNickname = nickname;
        commentForm.fromAvatar = avatar;
        commentForm.content = commentText.value;
        commentForm.createdAt = date;
        commentForm.updatedAt = date;
    }
};

// 重置当前评论对象
function resetForm() {
    for(let key in commentForm ) {
        commentForm[key] = '';
    }
    commentForm.parentId = '0';
    commentForm.type = props.commentType;
};

// 评论内容校验
function isValidComment(comment) {
    // 定义规则
    const rules = [
        { regex: /^ *$/, errorMsg: '评论内容不能为空！' },
    ];
    for (const rule of rules) {
        if (rule.regex.test(comment)) {
            ElMessage.error(rule.errorMsg);
            return false;
        };
    };
    return true;
};
</script>

<style lang="scss" scoped>
    @import './comment.scss';
    @import '@/theme/animations.scss';
</style>